<?php
/**
*+------------------APP 赛事控制器---------------+
*--------------------------------------------------+
*+-----------赛事信息的获取------------------------+
*+-------------------------------------------------+
*+-@author susy.liang <liangling@ilongyuan.com.cn>-+
*+-------------------------------------------------+
*/

namespace Api\Controller;

class MatchController extends PublicController 
{

	/**
	*赛事列表  该接口ios和android均可用
	*采用页码p进行分页
	*@author susy<susy.liang@ilongyuan.com.cn>
	*/
	public function index()
	{
		$mevtObj = A('Api/Match', 'Event');

		$total = $mevtObj->total();
		if($total){

			$p = I('p', 1, 'intval');
			$pager = I('pager', C('MATCH_INDEX_LIST',NULL, 20), 'intval');			
			$matchs = $mevtObj->lists($p, $pager);

			$data = array();
			if($matchs){

				$fieldMap = array('id','title','subtitle','logo','cover','create_time','game','race','detail','match_state');
				$gameMap = array('id', 'name', 'pic', 'background');

				$vdServ = D('Common/Video', 'Service');
				$curhour = date('H:i', time());
				$curDate = strtotime(date('Y-m-d', time()));
				
				foreach ($matchs as $key => $value) {

					uri_format($value['logo']);
					uri_format($value['cover']);
					$value['game'] = $this->field_filter($value['game'], $gameMap);

					//取比赛
					$filter = array(
							'match_id'=>intval($value['id']),
							'status'=>$vdServ::STATUS_PASS
						);
					if($value['match_state'] == 2){
						$filter['match_time'] = $curDate;
						$filter['match_hour'] = array('elt', $curhour);
						
					}
					$races = $vdServ->where($filter)->order('match_date asc,match_hour asc')
							->field('match_time,match_hour,competitor')->select();
					if($races){
						$races = array_pop($races);
						unset($races['_id']);
						$value['race'] = $races;
					}
					//end
					$data[] = $this->field_filter($value, $fieldMap);
				}
			}

		}
		$this->success('', array('list'=>$data,'total'=>$total));
	}


	/**
	*获取赛事下的比赛列表 , 旧接口， 保留给ios用
	*/
	public function lists(){

		$eventObj = A('Api/match', 'Event');

		$id = I('id', 0, 'intval');
		$match = $eventObj->info($id);
		if(empty($match))
			$this->error(self::$API_ERROR['MATCH'], '赛事信息有误');

		uri_format($match['teamlogo']);

		$map = array();
		$date = I('date','');
		if($date){
			$map['match_time'] = strtotime($date);
		}else{
			$defTime = $eventObj->getDefDate($id);
            $map['match_time'] = $defTime;
            $date = date('Y-m-d', $defTime);
		}

		$map['match_id'] = $id;
		$orderby = 'match_time desc, create_time desc';
		$matches = $eventObj->races($map, 0, 0, $orderby, '', true, $match['teamlogo']);

		$data = array();
		if($matches){
			$mapField = array('id', 'title', 'score', 'score_point', 'match_id', 'match_time', 'match_hour', 'team');
			foreach ($matches as $key => $value) {
				$data[] = $this->field_filter($value, $mapField);
			}
		}

		//$data = array('lists'=>$data, 'total'=>count($matches));
		$this->success('操作成功', $data);


	}

	/**
	*按照键值进行数据的组合分组 , 旧接口， 保留给ios用
	*@param array $data 待组合的数据
	*@param string $groupKey 分组的标识项
	*@param string $picFormat 图片的键名
	*@author susy<susy.liang@ilongyuan.com.cn>
	*/
	private function groupFormat($data=array(), $groupKey='', $picFormat=''){

		if(empty($data) || empty($groupKey))
			return false;

		$temp = array();
		foreach ($data as $key => $value) {

			if($picFormat)
				uri_format($value[$picFormat]);

			$temp[$value[$groupKey]][] = $value;
		}

		$res = array();
		foreach ($temp as $k => $val) {
			
			$res[] = array(
					'timeGroup'=>$k,
					'data'=>$val
					);
		}

		return $res;


	}

	/**
	*获取比赛下的视频明细信息 , 旧接口， 保留给ios用
	*获取条件是比赛标识
	*@author susy<susy.liang@ilongyuan.com.cn>
	*/
	public function detail(){

		$eventObj = A('Api/Match', 'Event');
		$cmtObj = A('Api/Comments', 'Event');

		$id = I('id', 0, 'intval');
		$uid = $this->getUid(I('appToken',''));
		$infos = $eventObj->videoOld($id, $uid);
		if(!$infos)
			$this->error(self::$API_ERROR['MATCH'], '比赛信息有误');

		$infos['action']['is_favour'] = intval(A('Api/Favour', 'Event')->isFavour($uid, $id));

		//取推荐数据
		$recommend = array();
		$map = array(
				'match_id' => intval($infos['match_id']),
				'match_time' => array('lt',$infos['match_time'])
			);
		$orderby = 'match_time desc, create_time desc';
		$matches = $eventObj->races($map, 0, C('MATCH_RELEVANT_LIST'), $orderby);
		if($matches){
			$mapField = array(
						'id', 'title', 'detail', 'score', 'score_point', 
						'match_id', 'match_time', 'match_hour', 'team'
						);
			foreach ($matches as $key => $value) {
				$recommend[] = $this->field_filter($value, $mapField);
			}
		}
		//end
		$fieldMap = array('id', 'thumb', 'title', 'score', 'score_point',
					'detail', 'create_time', 'videos', 'match_time','teams',
					'comments', 'action');
		$infos = $this->field_filter($infos, $fieldMap);

		$infos['comment'] = $cmtObj->get($id, 3, 'id,uid,nickname,content,create_time');
		$infos['recommend'] = $recommend;

		//浏览记录
		$uid && A('Api/History', 'Event')->add($uid, $id);
		
		$this->success('请求成功', $infos);
	}

	/**
	*获取赛事下的比赛的赛时列表 , 旧接口， 保留给ios用
	*@author susy<susy.liang@ilongyuan.com.cn>
	*/
	public function dateList(){

		$eventObj = A('Api/match', 'Event');

		$id = I('id', 0, 'intval');
		$pager = I('pager', 0, 'intval');
		$match = $eventObj->info($id);
		if(empty($match))
			$this->error(self::$API_ERROR['MATCH'], '赛事信息有误');

		$dates = $eventObj->matchDate($id, $pager);
		$this->success('获取成功', $dates);
	}


	/**
	*获取某一比赛的相关推荐 , 旧接口， 保留给ios用
	*@author susy<susy.liang@ilongyuan.com.cn>
	*/
	public function relevant(){

		$eventObj = A('Api/match', 'Event');

		$id = I('id', 0, 'intval');
		$infos = $eventObj->video($id);
		$infos = D('Common/Video', 'Service')->field('id,match_time,match_id')->find($id);
		if(empty($infos))
			$this->error(self::$API_ERROR['MATCH'], '比赛信息有误');

		$map = array(
				'match_id' => intval($infos['match_id']),
				'match_time' => array('lt',$infos['match_time'])
			);
		$orderby = 'match_time desc, create_time desc';
		$matches = $eventObj->races($map, 0, C('MATCH_RELEVANT_LIST'), $orderby);

		$data = array();
		if($matches){
			$mapField = array('id', 'title', 'score', 'score_point', 'match_id', 'match_time', 'match_hour', 'team');
			foreach ($matches as $key => $value) {
				$data[] = $this->field_filter($value, $mapField);
			}
		}
		
		$this->success('操作成功', $data);

	}

	/**
	*游戏下的赛事 , 旧接口， 保留给ios用
	*以时间戳分页 根据pager取列表数 获取某一游戏下的赛事
	*@author susy.liang<liangling@ilongyuan.com.cn>
	*/
	public function gameMatches(){

		$game = I('game', 0, 'intval');
		$gameInfo = A('Api/Game', 'Event')->info($game);
		if(!$gameInfo)
			$this->error(self::$API_ERROR['GAME'], '游戏信息有误');

		$timestamp = I('timestamp', 0, 'intval');
		$pager = I('pager', C('MATCH_INDEX_LIST',NULL, 20), 'intval');
		$matches = A('Api/Match', 'Event')->gameMatches($game, $timestamp, $pager);

		$data = array();
		if($matches){
			$fieldMap = array('id','title','subtitle','game_id','logo','cover','create_time','game', 'detail','match_state');
			foreach ($matches as $key => $value){
				uri_format($value['logo']);
				uri_format($value['cover']);
				unset($value['_id']);
				unset($value['game']);
				$data[] = $this->field_filter($value, $fieldMap);
			}

		}
		
		$this->success('操作成功', $data);
	}

//************以上接口为旧版比赛接口，保留给ios用*************
//************以下是新版比赛的接口****************************
	/**
	*赛事列表
	*采用页码p进行分页
	*@author susy<susy.liang@ilongyuan.com.cn>
	*/
	public function indexNew()
	{
		// $appToken = I('appToken', '', 'trim');
		// $appToken && $uid = $this->getUid($appToken);

		// if ($uid) {
		// 	$game_ids = event('GameScribe')->mine($uid);
		// }
		$mevtObj = A('Api/Match', 'Event');

		$total = $mevtObj->total();
		if($total){

			$p = I('p', 1, 'intval');
			$pager = I('pager', C('MATCH_INDEX_LIST',NULL, 20), 'intval');			

			// 添加$game_id参数  by liubo<liubo@ilongyuan.com.cn> at 2016-07-06
			$game_id = I('game_id', 0, 'intval');
			$matchs = $mevtObj->lists($p, $pager, true, '', $game_id ?: $game_ids);

			$data = array();
			if($matchs){

				$fieldMap = array('id','title','subtitle','logo','cover','game','detail','match_state');
				$gameMap = array('id', 'name', 'pic', 'background', 'logo');

				$vdServ = D('Common/Video', 'Service');
				$curhour = date('H:i', time());
				$curDate = strtotime(date('Y-m-d', time()));
				
				foreach ($matchs as $key => $value) {

					uri_format($value['logo']);
					uri_format($value['cover']);
					$value['game'] = $this->field_filter($value['game'], $gameMap);

					$data[] = $this->field_filter($value, $fieldMap);
				}
			}

		}
		$this->success('', array('list'=>$data,'total'=>$total));
	}

	/**
	*热门接口
	*返回热门直播列表 以及 热门比赛列表
	*热门比赛按照时间降序，最多取前15天赛事的所有比赛
	*/
	public function hot(){
		// $appToken = I('appToken', '', 'trim');
		// $appToken && $uid = $this->getUid($appToken);

		// if ($uid) {
		// 	$game_ids = event('GameScribe')->mine($uid);
		// }

		$liveData = $this->liveRace($game_ids);
		$hotData = $this->hotRace($game_ids);

		$data = array('live'=>$liveData, 'hot'=>$hotData);

		$this->success('操作成功', $data);
	}

	/**
	*热门比赛
	*/
	private function hotRace($game_ids = null){
		$data = array();

		$eventObj = A('Api/RaceGroup', 'Event');
		$curDate = date('Y-m-d', time());
		$map = array(
				'state'=>1,
				// 'race_date'=>array('lt', $curDate)
			);
		if (!empty($game_ids)) {
			$map['game_id'] = ['$in' => $game_ids];
		}
		$ids = $eventObj->lists($map, 'id', C('MATCH_INDEX_LIST'), 0, 'race_time desc');

		$fieldMap = array('id', 'title', 'subtitle', 'race_date', 'race_hour', 'score', 'team', 'game', 'list');
		foreach ($ids as $key => $value) {
			$detail = $eventObj->info($value['id']);
			$detail['score'] = $detail['score']?array_map('intval', explode('-', $detail['score'])):array();
			$detail['game'] = $this->field_filter($detail['game'], array('id','name','logo'));
			$detail = $this->field_filter($detail, $fieldMap);

			/*$items = $eventObj->sigleRace($value['id'], 'id,title,round', false, 2);
			$detail['list'] = $items;
*/
			$race[$detail['race_date']][] = $detail;
			
		}

		foreach ($race as $key => $value) {
			$data[] = array('date'=>$key, 'list'=>$value);
		}

		return $data;
	}

	/**
	*直播赛
	*/
	private function liveRace($game_ids = null){
		$data = array();

		$eventObj = A('Api/RaceGroup', 'Event');
		$map = array('race_date'=>date('Y-m-d', time()));
		if (!empty($game_ids)) {
			$map['game_id'] = ['$in' => $game_ids];
		}
		$ids = $eventObj->lists($map, 'id', 0, 0, 'race_time desc');

		foreach ($ids as $key => $value) {
			$detail = $eventObj->info($value['id']);
			$detail['game'] = $this->field_filter($detail['game'], array('id','name','logo'));
			array_push($data, $detail);
		}

		return $data;

	}


	/**
	*预告赛接口
	*以页码进行分页
	*/
	public function forcast(){
		// $appToken = I('appToken', '', 'trim');
		// $appToken && $uid = $this->getUid($appToken);

		// if ($uid) {
		// 	$game_ids = event('GameScribe')->mine($uid);
		// }

		$data = array();
		$eventObj = A('Api/RaceGroup', 'Event');
		$scribeObj = A('Api/RaceScribe', 'Event');

		$p = I('p', 1, 'intval');
		$pager = I('pager', C('MATCH_INDEX_LIST'), 'intval');
		$map = array(
				'race_date'=>array('gt', date('Y-m-d', time())),
				'status'=>1
			);
		if (!empty($game_ids)) {
			$map['game_id'] = ['$in' => $game_ids];
		}
		$ids = $eventObj->lists($map, 'id', $pager, $p, 'race_time asc');
		if(I('appToken'))
			$uid = $this->getUid(I('appToken'));

		$fieldMap = array('id', 'title', 'subtitle', 'race_date', 
					'race_hour', 'team', 'is_scribe', 'game'
					);
		$items = array();
		foreach ($ids as $key => $value) {
			$detail = $eventObj->info($value['id']);
			$detail['is_scribe'] = intval($scribeObj->is_scribe($uid, $value['id']));
			$detail['game'] = $this->field_filter($detail['game'], array('id','name','logo'));
			$detail = $this->field_filter($detail, $fieldMap);
			$items[$detail['race_date']][] = $detail;

		}
		foreach ($items as $key => $value) {
			$data[] = array('date'=>$key, 'list'=>$value);
		}

		$this->success('操作成功', $data);
	}

	/**
	*获取赛事下的比赛列表
	*取的是已经发布的比赛
	*以页码p进行分页
	*/
	public function listsNew(){

		$eventObj = A('Api/match', 'Event');

		$id = I('id', 0, 'intval');
		$match = $eventObj->info($id);
		if(empty($match))
			$this->error(self::$API_ERROR['MATCH'], '赛事信息有误');

		$game = A('Api/Game', 'Event')->info(intval($match['game_id']));
		uri_format($game['logo']);
		$game = $this->field_filter($game, array('id','name','logo'));

		uri_format($match['teamlogo']);
		uri_format($match['logo']);
		uri_format($match['cover']);
		$data = $this->field_filter($match, array('id', 'title', 'logo', 'cover','teamlogo'));
		

		
		$p = I('p', 1, 'intval');
		$pager = I('pager', C('MATCH_DETAIL_LIST'), 'intval');

		$eventObj = A('Api/RaceGroup', 'Event');
		$raceDates = $eventObj->raceTimeGroup($id, $p, $pager);
		if($raceDates){
			$map = array(
					'match_id'=>$id, 
					'state'=>1,
					'race_date'=>array('in', $raceDates)
					);
			$ids = $eventObj->lists($map, 'id', 0, 0, 'race_time desc');

			$race = array();
			$fieldMap = array('id', 'title', 'subtitle', 'race_date', 'race_hour', 'score', 'team', 'list');
			foreach ($ids as $key => $value) {
				$detail = $eventObj->info($value['id'], $match['teamlogo']);
				$detail['score'] = $detail['score']?array_map('intval', explode('-', $detail['score'])):array();
				$detail = $this->field_filter($detail, $fieldMap);

				/*$items = $eventObj->sigleRace($value['id'], 'id,title,round', false, 2);
				$detail['list'] = $items;*/

				$detail['game'] = $game;//游戏加入项内，保持结构同热门预告相同
				
				$race[$detail['race_date']][] = $detail;

			}
			$temp = array();
			foreach ($race as $key => $value) {
				$temp[] = array('date'=>$key, 'list'=>$value);
			}
			$data['race'] = $temp;
		}

		$this->success('操作成功', $data);

	}

	/**
	*获取赛事的赛程
	*@author susy.liang<liangling@ilongyuan.com.cn>
	*/
	public function schedule(){
		$eventObj = A('Api/match', 'Event');
		$id = I('id', 0, 'intval');
		$match = $eventObj->info($id);
		if(empty($match))
			$this->error('赛事信息有误');

		$version = I('version');
		$ret = $version == '2016' ? [
			'pic' 	   => $match['schepic'],
			'schedule' => $match['schedule'],
		] : $match['schedule'];

		$this->success('操作成功', $ret);

	}

	/**
	*获取比赛下的视频明细信息
	*获取条件是比赛标识
	*@author susy<susy.liang@ilongyuan.com.cn>
	*/
	public function detailNew(){

		$eventObj = A('Api/Match', 'Event');
		$cmtObj = A('Api/Comments', 'Event');

		$param = I('');
		$param = array_map('intval', $param);
		$id = $this->checkParam($param);

		$uid = $this->getUid(I('appToken',''));
		$infos = $eventObj->video($id, $uid);
		if(!$infos)
			$this->error(self::$API_ERROR['MATCH'], '比赛信息有误');

		$infos['action']['is_favour'] = intval(A('Api/Favour', 'Event')->isFavour($uid, $id));

		//取该比赛的所有小比赛数据
		$map = array(
				'group_id'=>intval($infos['group_id']),
				'status'=>1,
			);
		$raceSchedule = D('Common/Video', 'Service')->where($map)->field('id,title,round')
						->order('round asc')->select();
		$schedule = array();
		foreach ($raceSchedule as $key => $value) {
			unset($value['_id']);
			array_push($schedule, $value);
		}
		$infos['schedule'] = $schedule;
		//end

		$infos['recommend'] = $this->getRefer($infos['match_id'], $infos['group_id']);

		$comments = $cmtObj->get($id, 3, 'id,uid,nickname,content,create_time', [], false, $uid);
		$infos['comment'] = $comments?$comments:array();

		$fieldMap = array('id', 'thumb', 'title', 'score', 'total_score', 'round','detail', 
						'videos','team','comments', 'action', 'schedule', 'comment', 'recommend','game', 'race_date', 'race_hour'
						);
		$infos = $this->field_filter($infos, $fieldMap);
		uri_format($infos['game']['background']);
		//浏览记录
		$uid && A('Api/History', 'Event')->add($uid, $id);
		event('Video')->setPlay($infos['id'], 1, ['appid' => I('appid', 0, 'intval')]);

		$this->success('请求成功', $infos);
	}

	/**
	*获取比赛的相关推荐
	*@author susy.liang<liangling@ilongyuan.com.cn>
	*modify by liubo<liubo@ilongyuan.com.cn> at 2016-04-22
	*/
	private function getRefer($matchId=0, $raceId=0)
	{
		$recommend = [];
		$fieldMap = array('id', 'title', 'subtitle', 'race_date', 
					'race_hour', 'team', 'is_scribe', 'game', 'score', 'match'
					);
		$recommend = A('Api/RaceGroup', 'Event')->getReferRace($matchId, $raceId);
		$videoEvent = A('Api/Video', 'Event');
		foreach ($recommend as $key => $value) {
			$value['game'] = $this->field_filter($value['game'], array('id','name','logo'));
			$value['score'] = $value['score']?array_map('intval', explode('-', $value['score'])):array();
			$recommend[$key] = $this->field_filter($value, $fieldMap);
			uri_format( $recommend[$key]['match']['cover'] );


			$races = $videoEvent->lists(['group_id' => $recommend[$key]['id'], 'type' => 1], 0, true);
            if (!empty($races) && is_array($races)) {
                sort($races);
                $races = array_slice($races, 0, 4);
            }
            $recommend[$key]['match']['races'] = $races;
		}
		return $recommend ?: [];
	}

	/**
	*比赛视频明细参数检查
	*@param array $data 请求的参数
	*/
	private function checkParam($data=array()){
		if($data['race_id'])
		{
			$id = $data['race_id'];
		}
		elseif($data['group_id'])
		{
			$servObj = D('Common/Video', 'Service');
			$map = array(
					'group_id'=>$data['group_id'],
					'status'=>$servObj::STATUS_PASS,
					'type'=>$servObj::TYPE_MATCH
				);
			$races = $servObj->where($map)->order('round asc')->getField('id', true);
			return intval($races[0]);
		}
		else
		{
			$this->error(self::$API_ERROR['PARAM'], '参数错误');
		}

		return $id;
	}

}